<template>
  <div class="weapon-list">
    <div class="page-title">武器装备列表</div>

    <!-- 搜索和筛选 -->
    <div class="page-card filter-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="输入装备名称搜索"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="装备分类">
          <el-select
            v-model="searchForm.category"
            placeholder="全部分类"
            clearable
            style="width: 150px"
          >
            <el-option label="战斗机" value="战斗机" />
            <el-option label="坦克" value="坦克" />
            <el-option label="驱逐舰" value="驱逐舰" />
            <el-option label="航空母舰" value="航空母舰" />
            <el-option label="潜艇" value="潜艇" />
            <el-option label="直升机" value="直升机" />
            <el-option label="导弹" value="导弹" />
          </el-select>
        </el-form-item>
        <el-form-item label="原产国">
          <el-select
            v-model="searchForm.originCountry"
            placeholder="全部国家"
            clearable
            style="width: 150px"
          >
            <el-option label="美国" value="美国" />
            <el-option label="中国" value="中国" />
            <el-option label="俄罗斯" value="俄罗斯" />
            <el-option label="英国" value="英国" />
            <el-option label="法国" value="法国" />
            <el-option label="德国" value="德国" />
            <el-option label="日本" value="日本" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 装备列表 -->
    <div class="page-card list-section">
      <el-table
        :data="weaponList"
        v-loading="loading"
        style="width: 100%"
        stripe
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column label="缩略图" width="100" align="center">
          <template #default="{ row }">
            <el-image
              v-if="row.thumbnail"
              :src="`/${row.thumbnail}`"
              fit="cover"
              style="width: 80px; height: 60px; border-radius: 4px;"
              :preview-src-list="[`/${row.thumbnail}`]"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="装备名称" min-width="250">
          <template #default="{ row }">
            <div class="weapon-name">
              <div class="chinese-name">{{ row.chinese_name }}</div>
              <div class="english-name">{{ row.english_name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="origin_country" label="原产国" width="100" />
        <el-table-column label="简介" min-width="300" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.chinese_intro || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="service_time" label="服役时间" width="120" />
        <el-table-column prop="status" label="状态" width="100" />
        <el-table-column label="审核时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.audit_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row.id)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadWeaponList"
          @current-change="loadWeaponList"
        />
      </div>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="装备详情"
      width="80%"
      :destroy-on-close="true"
    >
      <div v-if="currentWeapon" class="weapon-detail">
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <!-- 缩略图 -->
            <div v-if="currentWeapon.basicInfo?.thumbnail" class="thumbnail-container">
              <el-image
                :src="`/${currentWeapon.basicInfo.thumbnail}`"
                fit="contain"
                style="width: 100%; max-height: 300px;"
                :preview-src-list="[`/${currentWeapon.basicInfo.thumbnail}`]"
              />
            </div>

            <el-descriptions :column="2" border style="margin-top: 20px;">
              <el-descriptions-item label="中文名称">
                {{ currentWeapon.basicInfo?.chinese_name || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="英文名称">
                {{ currentWeapon.basicInfo?.english_name || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="原产国">
                {{ currentWeapon.basicInfo?.origin_country || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="装备分类">
                {{ currentWeapon.basicInfo?.category || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="承包商">
                {{ currentWeapon.basicInfo?.contractor || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="服役时间">
                {{ currentWeapon.basicInfo?.service_time || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="状态" :span="2">
                {{ currentWeapon.basicInfo?.status || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="中文简介" :span="2">
                {{ currentWeapon.basicInfo?.chinese_intro || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="英文简介" :span="2">
                {{ currentWeapon.basicInfo?.english_intro || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="研制背景" :span="2">
                <div class="long-text">{{ currentWeapon.basicInfo?.development_background || '-' }}</div>
              </el-descriptions-item>
              <el-descriptions-item label="建造沿革" :span="2">
                <div class="long-text">{{ currentWeapon.basicInfo?.construction_history || '-' }}</div>
              </el-descriptions-item>
              <el-descriptions-item label="服役历程" :span="2">
                <div class="long-text">{{ currentWeapon.basicInfo?.service_history || '-' }}</div>
              </el-descriptions-item>
              <el-descriptions-item label="结构特征" :span="2">
                <div class="long-text">{{ currentWeapon.basicInfo?.structural_features || '-' }}</div>
              </el-descriptions-item>
              <el-descriptions-item label="配备装备" :span="2">
                <div class="long-text">{{ currentWeapon.basicInfo?.equipment || '-' }}</div>
              </el-descriptions-item>
              <el-descriptions-item label="动力系统" :span="2">
                <div class="long-text">{{ currentWeapon.basicInfo?.power_system || '-' }}</div>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <!-- 战技指标 -->
          <el-tab-pane label="战技指标" name="specs">
            <el-table
              v-if="currentWeapon.specifications && currentWeapon.specifications.length > 0"
              :data="currentWeapon.specifications"
              row-key="id"
              border
              default-expand-all
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
              :indent="20"
              style="width: 100%"
              class="tree-table-specs"
            >
              <el-table-column label="" width="50" align="center" />
              
              <el-table-column label="名称" min-width="250">
                <template #default="{ row }">
                  <span 
                    :class="row.node_type === 'category' ? 'category-name' : ''"
                  >
                    {{ row.indicator_chinese || row.indicator_english }}
                  </span>
                </template>
              </el-table-column>
              
              <el-table-column prop="indicator_english" label="英文名称" min-width="200">
                <template #default="{ row }">
                  <span v-if="row.node_type === 'indicator'">{{ row.indicator_english }}</span>
                  <span v-else class="text-muted">-</span>
                </template>
              </el-table-column>
              
              <el-table-column prop="indicator_value" label="指标值" min-width="180">
                <template #default="{ row }">
                  <span v-if="row.node_type === 'indicator'">{{ row.indicator_value }}</span>
                  <span v-else class="text-muted">-</span>
                </template>
              </el-table-column>
            </el-table>
            <el-empty v-else description="暂无战技指标" />
          </el-tab-pane>

          <!-- 使用用户 -->
          <el-tab-pane label="使用用户" name="users">
            <el-table
              :data="currentWeapon.users"
              border
              style="width: 100%"
            >
              <el-table-column prop="country" label="国家" width="120" />
              <el-table-column prop="variant" label="装备变体" width="180" />
              <el-table-column prop="operator_chinese" label="运营商中文" min-width="180" />
              <el-table-column prop="operator_english" label="运营商英文" min-width="180" />
              <el-table-column prop="order_quantity" label="订单数量" width="120" />
            </el-table>
            <el-empty v-if="!currentWeapon.users || currentWeapon.users.length === 0" description="暂无使用用户信息" />
          </el-tab-pane>

          <!-- 原始介绍 -->
          <el-tab-pane label="原始介绍" name="original">
            <div class="markdown-content" v-html="renderMarkdown(currentWeapon.rawRecord?.description)"></div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { weaponApi } from '@/api/weapon'
import { marked } from 'marked'
import DOMPurify from 'dompurify'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const weaponList = ref([])
const detailDialogVisible = ref(false)
const currentWeapon = ref(null)
const activeTab = ref('basic')

const searchForm = reactive({
  keyword: '',
  category: '',
  originCountry: ''
})

// 加载装备列表
const loadWeaponList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.keyword || undefined,
      category: searchForm.category || undefined,
      originCountry: searchForm.originCountry || undefined
    }

    const result = await weaponApi.getList(params)
    weaponList.value = result.data || []
    total.value = result.total || 0
  } catch (error) {
    ElMessage.error('加载失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadWeaponList()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.category = ''
  searchForm.originCountry = ''
  currentPage.value = 1
  loadWeaponList()
}

// 查看详情
const handleViewDetail = async (id) => {
  try {
    const result = await weaponApi.getDetail(id)
    if (result.success) {
      currentWeapon.value = result
      activeTab.value = 'basic'
      detailDialogVisible.value = true
    }
  } catch (error) {
    ElMessage.error('加载详情失败: ' + error.message)
  }
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 渲染 Markdown
const renderMarkdown = (markdown) => {
  if (!markdown) return '<p class="empty-text">暂无内容</p>'
  
  try {
    marked.setOptions({
      breaks: true,
      gfm: true
    })
    
    const html = marked.parse(markdown)
    return DOMPurify.sanitize(html)
  } catch (error) {
    console.error('Markdown 渲染失败:', error)
    return '<p class="error-text">Markdown 格式错误</p>'
  }
}

onMounted(() => {
  loadWeaponList()
})
</script>

<style lang="scss" scoped>
.weapon-list {
  .text-muted {
    color: #909399;
    font-size: 12px;
  }

  .category-name {
    font-weight: 600;
    color: #409eff;
    padding: 4px 8px;
    background-color: #ecf5ff;
    border-radius: 4px;
    border-left: 3px solid #409eff;
    display: inline-block;
  }

  // 树形表格样式增强
  .tree-table-specs {
    // 第一列展开按钮列
    :deep(.el-table__body) {
      .el-table__row {
        .el-table__cell:first-child {
          .cell {
            display: flex;
            align-items: center;
            padding: 0;
            padding-left: 0 !important;
          }
        }
      }
    }

    // 根据层级设置展开按钮左侧空白
    :deep(.el-table__indent) {
      display: inline-block;
      width: 20px;
      height: 1px;
    }

    // 展开按钮样式
    :deep(.el-table__expand-icon) {
      font-size: 14px;
      color: #409eff;
      margin-left: 5px;
      
      &:hover {
        color: #66b1ff;
      }
    }

    // 层级视觉辅助线
    :deep(.el-table__placeholder) {
      display: inline-block;
      width: 20px;
      height: 100%;
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        left: 10px;
        top: 0;
        bottom: 0;
        width: 1px;
        background-color: #dcdfe6;
      }
    }

    :deep(.el-table__row) {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }

  .filter-section {
    margin-bottom: 20px;

    .search-form {
      :deep(.el-form-item) {
        margin-bottom: 0;
      }
    }
  }

  .image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 60px;
    background-color: #f5f7fa;
    border-radius: 4px;
    color: #909399;
    font-size: 24px;
  }

  .weapon-name {
    .chinese-name {
      font-weight: 600;
      font-size: 15px;
      color: #303133;
    }

    .english-name {
      font-size: 13px;
      color: #909399;
      margin-top: 4px;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .weapon-detail {
    .thumbnail-container {
      margin-bottom: 20px;
      text-align: center;
      padding: 15px;
      background-color: #f5f7fa;
      border-radius: 8px;
    }

    .long-text {
      white-space: pre-wrap;
      line-height: 1.8;
      max-height: 300px;
      overflow-y: auto;
    }
  }

  .markdown-content {
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    max-height: 600px;
    overflow-y: auto;

    :deep(h1) {
      font-size: 24px;
      margin: 20px 0 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #eee;
    }

    :deep(h2) {
      font-size: 20px;
      margin: 18px 0 12px;
      padding-bottom: 8px;
      border-bottom: 1px solid #f0f0f0;
    }

    :deep(h3) {
      font-size: 18px;
      margin: 16px 0 10px;
    }

    :deep(p) {
      margin: 8px 0;
      line-height: 1.8;
    }

    :deep(ul), :deep(ol) {
      margin: 10px 0;
      padding-left: 25px;
    }

    :deep(li) {
      margin: 5px 0;
      line-height: 1.6;
    }

    :deep(table) {
      width: 100%;
      margin: 15px 0;
      border-collapse: collapse;

      th, td {
        padding: 8px 12px;
        border: 1px solid #ddd;
      }

      th {
        background-color: #f4f4f5;
        font-weight: bold;
      }
    }

    .empty-text {
      color: #909399;
      text-align: center;
      padding: 50px 0;
    }
  }
}
</style>
